<?php
namespace App\Admin\Controllers\CustomerDelivery;

use App\Importer\Basics\BImporter;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Models\Product\ProductSku;
use App\Models\Sys\Logs;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class DeliveryDemandUploadController extends AdminController{

    protected $title = '导入客户订单';

    protected function grid()
    {
        return view('customer-delivery.delivery-demand-upload.index');
    }

    public function upload(Request $request){

        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(), $file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $orders = [];
            $date = date('Y-m-d H:i:s', time());

            foreach($data as $row){
                $count++;
                $remarks = $row[0] ? trim($row[0]) : '';
                $orderNo = $row[1] ? trim($row[1]) : '';
                $_country = $row[2] ? trim($row[2]) : '';
                $reCountry = $row[3] ? trim($row[3]) : '';
                $receiver = $row[4] ? trim($row[4]) : '';
                $address = $row[5] ? trim($row[5]) : '';
                $state = $row[6] ? trim($row[6]) : '';
                $city = $row[7] ? trim($row[7]) : '';
                $postcode = $row[8] ? trim($row[8]) : '';
                $phone = $row[9] ? trim($row[9]) : '';
                $sku = $row[10] ? trim($row[10]) : '';
                $orderNum = $row[11] ? trim($row[11]) : 0;
                $orderChannel = $row[12] ? trim($row[12]) : 1;
                $orderType = $row[13] ? trim($row[13]) : 1;
                $platId = $row[14] ? trim($row[14]) : 0;
                if(!$orderNo || !$sku || !$_country){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                if(!$orderChannel || !$orderType || !isset($platId)){
                    $errors[$count] = '订单相关必填项,不能为空';
                    continue;
                }
                if (!in_array(isset($platId), SysPlat::options()->toArray())) {
                    return response()->json(['status' => false, 'message' => $errors[$count]. '平台异常!']);
                }

                $key = $orderNo.'-'.$sku;
                if(!in_array($key, $arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }

                $country = strtoupper($_country);
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $country.'系统不存在该发货国家';
                    continue;
                }
                $areaId = SysCountry::getAreaIdByCountryId($countryId);
                if(!$areaId){
                    $errors[$count] = $country.'系统不存在该（国家）发货站点';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku, 'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在该sku';
                    continue;
                }

                $reCount = CustomerOrderDetails::query()->where('order_no', $orderNo)->where('psku_id', $pSkuId)->count();
                if($reCount > 0){
                    $errors[$count] = $key.'系统已存在，无需导入';
                    continue;
                }

                //组装订单相关数据
                if(!array_key_exists($orderNo, $orders)){
                    //订单
                    $orders[$orderNo] = [
                        'order_no' => $orderNo,
                        'order_at' => $date,
                        'order_channel' => $orderChannel,   //订单渠道(1.C端，2.B端)
                        'order_type' => $orderType,         //订单类型(1.订单，2.寄样)
                        'plat_id' => $platId,     //订单平台(0:无 1:FBA亚马逊 2:shopify 3:乐天)
                        'area_id' => $areaId,     //发货站点
                        'country_id' => $countryId,     //发货国家
                        'country_code' => $country,     //发货国家编码
                    ];
                }else{
                    if(!$orders[$orderNo]['order_no'] && $orderNo){
                        $orders[$orderNo]['order_no'] = $orderNo;
                    }
                    if(!$orders[$orderNo]['order_at'] && $date){
                        $orders[$orderNo]['order_at'] = $date;
                    }
                    if(!$orders[$orderNo]['order_channel'] && $orderChannel){
                        $orders[$orderNo]['order_channel'] = $orderChannel;
                    }
                    if(!$orders[$orderNo]['order_type'] && $orderType){
                        $orders[$orderNo]['order_type'] = $orderType;
                    }
                    if(!$orders[$orderNo]['plat_id'] && $platId){
                        $orders[$orderNo]['plat_id'] = $platId;
                    }
                    if(!$orders[$orderNo]['area_id'] && $areaId){
                        $orders[$orderNo]['area_id'] = $areaId;
                    }
                    if(!$orders[$orderNo]['country_id'] && $countryId){
                        $orders[$orderNo]['country_id'] = $countryId;
                    }
                    if(!$orders[$orderNo]['country_code'] && $country){
                        $orders[$orderNo]['country_code'] = $country;
                    }
                }

                //地址
                $orders[$orderNo]['receivers'][] = [
                    'country' => $reCountry,
                    'receiver' => $receiver,
                    'address' => $address,
                    'state' => $state,
                    'city' => $city,
                    'postcode' => $postcode,
                    'phone' => $phone,
                ];
                //明细
                $orders[$orderNo]['detail'][] = [
                    'plat_id' => $platId,
                    'psku_id' => $pSkuId,
                    'order_num' => $orderNum,
                    'apply_num' => 0,
                ];
            }
            if(empty($orders)){
                $errors[] = '本次上传文件未能导入系统：无符合条件的数据';
            }

            if(empty($errors)){
                foreach ($orders as $order){

                    DB::beginTransaction();
                    $detail = array_pop($order); //订单明细
                    $receivers = array_pop($order); //订单地址

                    $obj = CustomerOrder::query()->create($order);
                    $obj->detail()->createMany($detail);
                    $obj->receiver()->create($receivers[0]);
                    if($obj){
                        Logs::logs('customer-order', "创建消费订单(自建)：{$orderNo}", $obj->id);
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }
                }

                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(QueryException $qe){
            DB::rollBack();
            report($qe);
            return ['flag' => false,'data' => '操作失败！'];
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
